package com.unionpay.upyzt.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * 信息摘要工具类
 */
public class MessageDigestUtils {

    public static String sha256(File file) {
        try {
            return getHash(file, "SHA-256");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

//    public static String sha256(byte[] file) {
//        try {
//            return getHash(file, "SHA-256");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "";
//        }
//    }
//
//    private static String getHash(byte[] bytes, String hashType) throws Exception {
//            MessageDigest md5 = MessageDigest.getInstance(hashType);
//            md5.update(bytes);
//            return byte2Hex(md5.digest());
//    }

    private static String getHash(File file, String hashType) throws Exception {
        try(InputStream fis = new FileInputStream(file)){
            byte buffer[] = new byte[1024];
            MessageDigest md5 = MessageDigest.getInstance(hashType);
            for (int numRead = 0; (numRead = fis.read(buffer)) > 0; ) {
                md5.update(buffer, 0, numRead);
            }
            return byte2Hex(md5.digest());
        } catch (Exception e) {
            throw e;
        }
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                sb.append("0");
            }
            sb.append(temp);
        }
        return sb.toString();
    }

}
